﻿using WenAntdUI.Controls;
using WenAntdUI.Helps;

namespace WenAntdUI.Services;

public class MenuService(IFreeSql fsql, IdentityService identity)
{
    private List<SysMenu>? sysMenus;

    public List<SysMenu> SysMenus => sysMenus ??= fsql.Select<SysMenu>().ToTreeList();
    public List<SysMenu> GetSysMenus() => fsql.Select<SysMenu>().ToTreeList();




    /// <summary>
    /// 获取用户菜单
    /// </summary>
    /// <returns></returns>
    public List<MenuTagItem> GetUserMenuTagItems()
    {
        var username = identity.UserName;
        var menus = fsql.Select<SysUserRole, SysRoleMenu, SysMenu>()
            .LeftJoin(w => w.t1.RoleName == w.t2.RoleName)
            .LeftJoin(w => w.t2.MenuCode == w.t3.Code)
            .Where(w => w.t1.UserName == username)
            .OrderBy(w => w.t3.OrderNo)
            .ToList(w => w.t3);
        return GetMenuItems(menus.ConvertToTree(t => t.Code, t => t.ParentCode, t => t.Child));
    }
    /// <summary>
    /// 获取全部菜单
    /// </summary>
    /// <returns></returns>
    public List<MenuTagItem> GetMenuTagItemsAll()
    {
        return GetMenuItems(SysMenus);
    }

    private List<MenuTagItem> GetMenuItems(List<SysMenu> sysMenus)
    {
        var items = new List<MenuTagItem>();
        foreach (var menu in sysMenus)
        {
            if (menu.MenuType == MenuType.Menu)
            {
                var item = new MenuTagItem(menu.Code, menu.Name, menu.Icon);
                if (menu.Child?.Count > 0)
                {
                    item.Sub = GetMenuItems(menu.Child);
                }

                if (menu.ControlType != null)
                {
                    var type = Type.GetType(menu.ControlType);
                    if (type != null)
                        item.PageType = type;
                }
                items.Add(item);
            }
        }
        return items;
    }
}
